//
//  QCHomePictureView.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/5.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit
import SDWebImage

// cell 可重用标识符
private let pictureViewCellId = "pictureViewCellId"
// 各张图片之间的间距
private let itemMargin: CGFloat = 5
// 获取每张图片的宽高(正方形)
private let itemWH: CGFloat = (KSCREENW - 2*10 - 2*itemMargin)/3

class QCHomePictureView: UICollectionView {

    var pic_urls: [QCPictureModel]?{
        didSet{
            //获取配图的size
            let size = dealPictureViewSize(count: pic_urls?.count ?? 0)
            //设置约束
//            self.snp.updateConstraints { (make) in
//                make.size.equalTo(size)
//            }
            self.snp.makeConstraints { (make) in
                
               make.size.equalTo(size)
                
            }
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            //单张图片
            if pic_urls?.count == 1 {
                layout.itemSize = size
                
            }else {
                //多张图片
                layout.itemSize = CGSize(width: itemWH, height: itemWH)
            }
            // 因为itemSize的宽度和配图的宽度没有同步导致打印错误 需要解决该问题 需要重新刷新ui
            layoutIfNeeded()
            //刷新UI
            reloadData()
            
        }
    }
   //通过图片张数来计算size
    func dealPictureViewSize(count:Int)->CGSize{
        //如果是单张图片
        if count == 1 {
            //判断图片地址是否为nil
            if let picUrlString = pic_urls?.first?.thumbnail_pic {
                
                //在本地拿到下载下来的图片
                if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picUrlString) {
                    //得到本地图片的真实大小
                    var h = image.size.height
                    var w = image.size.width
                    //判断 w <80 默认80
                    if w < 80 {
                        w = 80
                    }
                    //判断 h>150 默认150
                    if h > 150 {
                        h = 150
                    }
                    return CGSize(width: w, height: h)
                }
            }
        }
        
        //不是1张 就通过 张数来计算行和列
          //如果是4 就两列 大于3 就三列  小于3 是几就几列
        let col = count == 4 ? 2 : count > 3 ? 3 : count
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        
        // 计算配图的宽和高
        let w = CGFloat(col)*itemWH + CGFloat(col - 1)*itemMargin
        let h = CGFloat(row)*itemWH + CGFloat(row - 1)*itemMargin
        
        return CGSize(width: w, height: h)
    }
    
   override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
         //设置size
        flowLayout.itemSize = CGSize(width: itemWH, height: itemWH)
        //设置间距
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
    
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        dataSource = self
        register(QCHomePictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        
    }
    

}
///数据源方法
extension QCHomePictureView: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureViewCellId, for: indexPath) as!QCHomePictureViewCell
        cell.pic_url = pic_urls![indexPath.item]
        return cell
    }
    
}

class QCHomePictureViewCell: UICollectionViewCell {
    //监听
    var pic_url: QCPictureModel?{
        didSet{
           bgImageView.setImage(urlString: pic_url?.thumbnail_pic)
        }
    }
    //init方法
 override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //添加控件
        contentView.addSubview(bgImageView)
        //约束
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
    private lazy var bgImageView: UIImageView = {
       let image = UIImageView(imageName: "avatar_default_big")
        //填充模式
        image.contentMode = .scaleAspectFill
        //超出部分裁掉
        image.clipsToBounds = true
        return image
    }()
    
}
